// checkout.js


// 修改订单提交函数
function submitOrder() {
    const addressId = document.getElementById('selectedAddressId').value;
    if (!addressId) {
        alert('请选择收货地址');
        return;
    }

    const cartItemIds = JSON.parse(sessionStorage.getItem('checkoutItems') || '[]');
    if (cartItemIds.length === 0) {
        alert('没有可结算的商品');
        return;
    }

    const userId = sessionStorage.getItem('userId');
    const orderRequest = {
        userId: parseInt(userId),
        addressId: parseInt(addressId),
        cartItemIds: cartItemIds
    };

    fetch('/api/order/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(orderRequest)
    })
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => { throw new Error(text) });
            }
            return response.json();
        })
        .then(order => {
            alert(`订单创建成功! 订单号: ${order.orderNo}`);
            sessionStorage.removeItem('checkoutItems');
            window.location.href = 'orderDetail.html?orderId=' + order.id;
        })
        .catch(error => {
            console.error('Error:', error);
            alert('创建订单失败: ' + (error.message || '服务器错误'));
        });
}









// 修改商品信息加载部分
document.addEventListener('DOMContentLoaded', function() {
    const userId = sessionStorage.getItem('userId');
    if (!userId) {
        window.location.href = 'cartList.html';
        return;
    }

    // 获取地址列表
    fetch(`/api/order/addresses?userId=${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取地址失败');
            }
            return response.json();
        })
        .then(addresses => {
            renderAddresses(addresses);
        })
        .catch(error => {
            console.error('获取地址失败:', error);
        });

    // 获取购物车商品信息
    const cartItemIds = JSON.parse(sessionStorage.getItem('checkoutItems') || '[]');
    if (cartItemIds.length > 0) {
        fetch(`/api/cart/items?ids=${cartItemIds.join(',')}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取商品信息失败');
                }
                return response.json();
            })
            .then(items => {
                renderOrderItems(items);
                calculateOrderSummary(items);
            })
            .catch(error => {
                console.error('获取商品信息失败:', error);
            });
    } else {
        alert('没有可结算的商品');
        window.location.href = 'cartList.html';
    }

    // 地址选择事件处理
    document.getElementById('addressList').addEventListener('click', function(e) {
        const addressItem = e.target.closest('.address-item');
        if (addressItem) {
            document.querySelectorAll('.address-item').forEach(item => {
                item.classList.remove('selected');
            });
            addressItem.classList.add('selected');
            document.getElementById('selectedAddressId').value = addressItem.dataset.addressId;
        }
    });

    // 提交订单按钮事件处理
    document.getElementById('submitOrderBtn').addEventListener('click', submitOrder);
});


// 修改renderAddresses函数
function renderAddresses(addresses) {
    const addressList = document.getElementById('addressList');
    if (addresses.length === 0) {
        addressList.innerHTML = `
            <div class="no-address">
                <p>您还没有添加收货地址</p>
                <button onclick="window.location.href='address.html'">添加地址</button>
            </div>
        `;
        return;
    }

    // 确保默认地址排在第一位
    addresses.sort((a, b) => (a.dfault === 0 ? -1 : 1));

    addressList.innerHTML = addresses.map(address => `
        <div class="address-item" data-address-id="${address.id}">
            <div class="address-info">
                <h4>${address.name} <span>${address.phone}</span></h4>
                <p>${address.province} ${address.city} ${address.district} ${address.addr}</p>
            </div>
            ${address.dfault === 0 ? '<span class="default-tag">默认</span>' : ''}
        </div>
    `).join('');

    // 默认选中第一个地址（应该是默认地址）
    if (addresses.length > 0) {
        const defaultAddress = addresses.find(a => a.dfault === 0) || addresses[0];
        const addressElement = document.querySelector(`.address-item[data-address-id="${defaultAddress.id}"]`);
        if (addressElement) {
            addressElement.classList.add('selected');
            document.getElementById('selectedAddressId').value = defaultAddress.id;
        }
    }
}

// 获取购物车商品信息
const cartItemIds = JSON.parse(sessionStorage.getItem('checkoutItems') || '[]');
if (cartItemIds.length > 0) {
    fetch(`/api/cart/items?ids=${cartItemIds.join(',')}`)
        .then(response => response.json())
        .then(items => {
            renderOrderItems(items);
            calculateOrderSummary(items);
        });
}

// 修改商品信息渲染函数
function renderOrderItems(items) {
    const orderItemsBody = document.getElementById('orderItemsBody');
    if (!items || items.length === 0) {
        orderItemsBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">没有商品信息</td></tr>';
        return;
    }

    orderItemsBody.innerHTML = items.map(item => `
        <tr>
            <td>
                <div class="order-item-info">
                    
                    <span class="order-item-name">${item.product.name}</span>
                </div>
            </td>
            <td>¥${item.product.price.toFixed(2)}</td>
            <td>${item.quantity}</td>
            <td>¥${(item.product.price * item.quantity).toFixed(2)}</td>
        </tr>
    `).join('');
}

// 计算订单总金额函数
function calculateOrderSummary(items) {
    if (!items || items.length === 0) {
        document.getElementById('totalPrice').textContent = '¥0.00';
        document.getElementById('freight').textContent = '¥0.00';
        document.getElementById('paymentAmount').textContent = '¥0.00';
        return;
    }

    const totalPrice = items.reduce((sum, item) => {
        return sum + (item.product.price * item.quantity);
    }, 0);

    // 假设运费固定为10元
    const freight = 10;
    const paymentAmount = totalPrice + freight;

    document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
    document.getElementById('freight').textContent = `¥${freight.toFixed(2)}`;
    document.getElementById('paymentAmount').textContent = `¥${paymentAmount.toFixed(2)}`;
}







